﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Grocery
{
    class Store
    {
        private List<CashierQueue> list; //Cashier Queue List;

        internal Store(int registers)
        {
            list = new List<CashierQueue>();
            for (int i = 1; i <= registers; ++i)
            {
                if (i == registers)
                {
                    list.Add(new CashierQueue(i, (int)CashierType.Training)); //Traing
                }
                else
                {
                    list.Add(new CashierQueue(i, (int)CashierType.Common));//
                }
            }

            DebugInfo.Ouput("t=0, Simulation starts with registers :" 
                + registers.ToString()
                + " #" + registers.ToString() + "is a training register.");
        }

      
        private bool AllQueueIsEmpty
        {
            get
            {
                foreach (CashierQueue q in list)
                {
                    if (!q.IsEmpty)
                    {
                        return false;
                    }
                }
                return true;
            }
        }

        private int Service(int minutes)
        {
            for (int i = 0; i < minutes; ++i)
            {
                foreach (CashierQueue q in list)
                {
                    q.Service();
                }
            }

            return minutes;
        }

        private int GetLeftMinutes()
        {
            int services = 0;

            while (!AllQueueIsEmpty)
            {
                services += Service(1);
            }

            return services;
        }

        internal int Simulate(IList<Customer> customers)
        {
            int lastStatus = 0;
            int offset = 0;

            foreach (Customer c in (from c in customers
                     orderby c.Offset, c.Items, c.customerType
                     select c ))
            {
                if (lastStatus != 0 && offset < c.Offset )
                {
                    Service(c.Offset - lastStatus);
                }

                c.AppendToQueue(c.Offset , list);

                offset = c.Offset;
                lastStatus = c.Offset;
            }

            return lastStatus + GetLeftMinutes();
        }
    }
}
